package com.hs.core.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.hs.auth.AUTHConstant;
import com.hs.auth.model.HsAccount;

public class SessionFilter implements Filter{
	/**
	 * Log4J Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(SessionFilter.class);

	public void init(FilterConfig cfg) throws ServletException {
	}
	
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
	{
		
		HttpServletRequest httprequest = (HttpServletRequest)request;
		HttpServletResponse httpresponse = (HttpServletResponse)response;
		
		String url = httprequest.getRequestURL().toString();
		if (logger.isDebugEnabled()) {
			logger.debug("URL-Filter:" + url);
		} 
		if(url.indexOf("/logon.jsp")!=-1||url.indexOf("/export.do")!=-1 ||url.indexOf("/logon2")!=-1  ||url.indexOf("/logon.jsp")!=-1 || url.indexOf("/logon.do")!=-1 || url.indexOf("/register.do") != -1 )
		{   
			if (logger.isDebugEnabled()) {
				logger.debug("登录请求");
			} 
	    	chain.doFilter(httprequest,httpresponse);
		}
		else
		{ 
			/**
			 * 判断用户是否为null
			 * 为null返回登录页
			 */
			
			HsAccount sessionuser = (HsAccount) httprequest.getSession().getAttribute(
					AUTHConstant.USERINSESSION);
			logger.debug("SEEESIONUSER:" + sessionuser);
			if(sessionuser != null)
				chain.doFilter(httprequest,httpresponse);
			else 
			{
				if(url.indexOf("/logout2.do")!=-1)
					httprequest.getRequestDispatcher("/logon2.jsp").forward(httprequest, httpresponse);
				else
					httprequest.getRequestDispatcher("/logon.jsp").forward(httprequest, httpresponse);
			}
		}
	}

	
	public void destroy() {
	
	}

}
